package com.example.goods_manage.controller;

import cn.hutool.core.io.IoUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * <P> @Author: SongKeCheng
 * <P> Type: Class
 * <P> Description: 处理文件的控制器
 * <P> Date: 2024/7/11:10:22
 */

@SuppressWarnings({"unchecked", ""})
@RequestMapping("/file")
@RestController
public class FileController {
    private static final Logger log = LoggerFactory.getLogger(FileController.class);


    /**
     *  设置上传文件存储的目录，应与上传文件的目录相同
     *  这个文件夹在f盘下：f:/path/to/your/upload/folder/
     *  应该跟当前项目在哪个盘有关系
    */
    private static String UPLOAD_FOLDER = "/path/to/your/upload/folder/";
    static {
        File file = new File(UPLOAD_FOLDER);
        if(!file.exists()){
            file.mkdirs();
        }
    }
    /**
     * 使用spring 的  ResponseEntity + Resource去自己读取
     * @GetMapping("/getImage/{filename:.+") 注解表示处理GET请求，并且 {filename:.+} 表示该路径参数可以包含点号以及后面的文件扩展名。
     */
    @GetMapping("/getImage/{filename:.+}")
    @ResponseBody
    public ResponseEntity<Resource> getImage(@PathVariable String filename) throws IOException {
        // 读取图片文件
        Path filePath = Paths.get(UPLOAD_FOLDER).resolve(filename);
        Resource resource = new org.springframework.core.io.FileSystemResource(filePath);

        // 返回图片作为响应
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_TYPE, MediaType.IMAGE_JPEG_VALUE)
                .body(resource);
    }
    /**
     * 使用读取文件的方式 使用 response 写回去
    */
    @GetMapping("/getImage2/{filename:.+}")
    public void getImageTwoVersion(@PathVariable String filename, HttpServletResponse response) throws IOException {

        // 读取图片文件
        Path filePath = Paths.get(UPLOAD_FOLDER).resolve(filename);
        File file = new File(UPLOAD_FOLDER+filename);
        FileInputStream fileInputStream = new FileInputStream(file);
        IoUtil.copy(fileInputStream,response.getOutputStream());
    }

    private static final String FILE_DIRECTORY = "D:/files/";  // 文件存储目录，根据实际情况修改

    /**
     * 通过文件名称来下载文件
     * 好像下载的速度局限在于你的网速 跟局域网好像没啥关系
    */
    @GetMapping("/download/{fileName:.+}")
    public ResponseEntity<Resource> downloadFile(@PathVariable String fileName) throws MalformedURLException {

        Path filePath = Paths.get(FILE_DIRECTORY).resolve(fileName).normalize();
        Resource resource = new UrlResource(filePath.toUri());

        if (!resource.exists()) {
            throw new RuntimeException("File not found: " + fileName);
        }

        // 设置下载响应
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"");

        return ResponseEntity.ok()
                .headers(headers)
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(resource);
    }
}
